package com.github.pagehelper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SQLUtil {
	/**
	 * 去除sql的select 子句，未考虑union的情况,用于pagedQuery.
	 *
	 */
	public static String removeSelect(final String sql){
		String sql_ = sql.toLowerCase().replaceAll("\\bfrom\\b", "@");
		int beginPos = sql_.indexOf('@');
		return sql.substring(beginPos);
	}
	/**
	 * 去除sql的orderby 子句，未考虑union的情况,用于pagedQuery.
	 *
	 */
	public static String removeOrders(String sql) {
		Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(sql);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			m.appendReplacement(sb, "");
		}
		m.appendTail(sb);
		return sb.toString();
	}
	public static void main(String[] args) {
		String sqlString = "select f,f2,r from t1 order by f union select f,f2,r from t2 order by f2";
		
		System.out.println(removeOrders(sqlString));
	}
}
